package com.yixiu.study.juc.taobao.num1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @CalssName T02_CountDownLatch
 * @Description
 * @Author yixiu
 * @Date 2021/6/25 10:34
 * @Verison num1.0
 **/
public class T02_CountDownLatch {

    volatile List lists = new ArrayList();

    public void add(Object o){
        lists.add(o);
    }

    public int size(){
        return lists.size();
    }

    public static void main(String[] args) {
        T02_CountDownLatch c = new T02_CountDownLatch();
        CountDownLatch latch = new CountDownLatch(1);

        //需要注意先启动线程t2再启动线程t1
        new Thread(() -> {
            System.out.println("t2 启动");
            if(c.size() != 5){
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2 结束");
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");

            for (int i = 0; i < 10; i++) {
                c.add(new Object());
                System.out.println("add" + i);
                if(c.size() == 5){
                    //暂停t1线程，打开门闩，让t2得以执行
                    latch.countDown();
                }

                //需要睡眠1s，让t2能够监控到latch变为0，让t2结束
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t1 结束");
        }, "t1").start();


    }


}
